package com.wzy.spring2.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @description:
 * @author: weizhengyun
 * @time: 2023/1/15-14:51
 **/

@Configuration
public class DbConfiguration {

    @Autowired
    private DbProperties dbProperties;

    @Primary
    @Bean("druidDataSource")
    public DataSource mysqlDataSource(){
        DruidDataSource dataSource =  new DruidDataSource();
        dataSource.setUrl(dbProperties.getUrl());
        dataSource.setUsername(dbProperties.getUserName());
        dataSource.setPassword(dbProperties.getPassword());
        return dataSource;
    }

    @Bean("mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("druidDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        return sqlSessionFactoryBean.getObject();
    }

    @Bean("aaaMysqlTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("druidDataSource") DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        return transactionManager;
    }
}
